//
//  TCWebCodesBridge.m
//  Test
//
//  Created by miao on 2021/3/24.
//

#import "TCWebCodesBridge.h"
typedef void(^Callback)(NSDictionary *resultJSON, BOOL success);
@interface TCWebCodesBridge ()

@property (nonatomic, strong) WKWebView *webView;
@property (nonatomic, strong) NSString  *appid;
@property (nonatomic, strong) UIView  *contentView;
@property (nonatomic, copy) Callback callback;
@end

@implementation TCWebCodesBridge

- (void) loadTencentCaptcha:(UIView*)view appid:(NSString*)appid callback:(void (^)(NSDictionary *result,BOOL success))callback
{
    CGFloat width = CGRectGetWidth(view.frame);
    CGFloat height = CGRectGetHeight(view.frame);
    if (width < 261.0 || height < 261) {
        NSLog(@"腾讯防水墙初始化失败，添加防水墙容器的宽度和高度不能小于261！！！");
        return;
    }
    
    self.contentView = view;
    self.callback = callback;
    if (!_webView) {
        WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
        configuration.userContentController = [WKUserContentController new];
        //注册果断回调方法
        [configuration.userContentController addScriptMessageHandler:self name:@"loadAction"];
        [configuration.userContentController addScriptMessageHandler:self name:@"errorAction"];
        [configuration.userContentController addScriptMessageHandler:self name:@"verifiedAction"];
        
        WKWebView* webView = [[WKWebView alloc] initWithFrame:CGRectZero configuration:configuration];
        webView.navigationDelegate = self;
        _webView = webView;
        [self.contentView addSubview:self.webView];
    };
    [self loadTencentCaptcha];
}

// 加载入口方法
- (void)loadTencentCaptcha {
    NSString *randomstr = [[NSUUID UUID] UUIDString];
    NSString *sdkOpts = @"{\"sdkOpts\": {\"width\": 140, \"height\": 140}}";
    NSString *appid = @"6780041320132784128";
    NSString* htmlText = [NSString stringWithFormat:DSWebBridge_html_js(),randomstr,sdkOpts,appid];
    [self.webView loadHTMLString:htmlText baseURL:nil];
}

//js调用原生回调
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
    if ([message.name isEqualToString:@"loadAction"]) {
        //加载成功, 更新webview的frame
        NSDictionary *jsData =  message.body;
        NSLog(@"loadAction = %@",jsData);
        self.webView.bounds = CGRectMake(0, 0, [jsData[@"sdkView"][@"width"] doubleValue], [jsData[@"sdkView"][@"height"] doubleValue]);
        self.webView.center = CGPointMake(self.contentView.bounds.size.width * 0.5, self.contentView.bounds.size.height * 0.5);
       
    }else if([message.name isEqualToString:@"verifiedAction"]) {
        //划动验证
        NSDictionary *jsData =  message.body;
        NSLog(@"verifiedAction = %@",jsData);
        !self.callback? : self.callback(jsData,YES);
        [self.webView removeFromSuperview];
        self.webView = nil;
        self.callback = nil;
    }else if([message.name isEqualToString:@"errorAction"]) {
        //加载失败
        NSDictionary *jsData =  message.body;
        NSLog(@"errorAction = %@",jsData);
        !self.callback? : self.callback(nil,NO);
        [self.webView removeFromSuperview];
        self.webView = nil;
        self.callback = nil;
    }
}


NSString * DSWebBridge_html_js() {
#define __wvjb_js_func__1(x) #x
    static NSString * html = @__wvjb_js_func__1(
                                                <!DOCTYPE html>
                                                <html>
                                                <head>
                                                <meta charset="utf-8">
                                                <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
                                                <title></title>
                                                <script src="https://ssl.captcha.qq.com/TCaptcha.js?v=%@"></script>
                                                </head>
                                                <body>
                                                <script type="text/javascript">
                                                (function(){

        // 验证成功返回ticket
        window.SDKTCaptchaVerifyCallback = function (retJson) {
            if (retJson){
                window.webkit.messageHandlers.verifiedAction.postMessage(retJson)
            }
        };
        
        // 验证码加载完成的回调，用来设置webview尺寸
        window.SDKTCaptchaReadyCallback = function (retJson) {
            if (retJson && retJson.sdkView && retJson.sdkView.width && retJson.sdkView.height &&  parseInt(retJson.sdkView.width) >0 && parseInt(retJson.sdkView.height) >0 ){
                window.webkit.messageHandlers.loadAction.postMessage(retJson)
            }
        };
        window.onerror = function (msg, url, line, col, error) {
            if (window.TencentCaptcha == null) {
                window.webkit.messageHandlers.errorAction.postMessage(error)
            }
        };
        var sdkOptions = %@;
        sdkOptions.ready = window.SDKTCaptchaReadyCallback;
        window.onload = function () {
            //此处需要替换xxxxxx为appid
            new TencentCaptcha("%@", SDKTCaptchaVerifyCallback, sdkOptions).show();
        };
    })();
                                                </script></body></html>
                                                );
#undef __wvjb_js_func__
    return html;
};

@end
